<template>
  <div class="roles">
    <!-- 面包屑导航位置 -->
    <bread :linktitle="link"></bread>
    <!-- 面包屑导航位置 -->

    <!--角色列表 -->
    <div class="right_wrap" v-if="tableData.length">
      <el-button type="primary" style="margin-bottom:20px" @click="openadd">添加角色</el-button>
      <el-table :data="tableData" border height="500" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row type="flex" justify="center" align="middle" v-for="(item,index) in props.row.children" :key="item.id" :class="['bdbottom',index == 0 ?'bdtop':'']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeright(props.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
                <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row  v-for="(items,ind) in item.children" :key="items.id" :class="['bdtop',ind == 0 ?'nobdtop':'']" >
                    <el-col :span="6">
                        <el-tag type="success" closable @close="removeright(props.row,items.id)">{{items.authName}}</el-tag>
                         <i class="el-icon-caret-right"></i>  
                    </el-col>
                    <el-col :span="10">
                      <el-tag  closable @close="removeright(props.row,itemd.id)" type="warning" v-for="(itemd,index) in items.children" :key="itemd.id" style="margin-right:10px">
                        {{itemd.authName}}
                      </el-tag>
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button type="primary" icon="el-icon-edit" size="mini"
                @click="openedit(scope.row)">编辑</el-button
              >
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            
            >
              <el-button type="danger" icon="el-icon-delete" size="mini"  @click="del(scope.row.id)"
                >删除</el-button
              >
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" size="mini"
                @click="openrole(scope.row)">分配权限</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 角色列表 -->

   <!-- 编辑角色信息 -->
<div style="text-align:left">
  <el-dialog
  title="提示"
  :visible.sync="dialogVisible"
  width="30%">
  <span>
    <el-tree
  :data="roledata"
  show-checkbox
  node-key="id"
  :props="defaultProps"
  :default-checked-keys="roleid"
  ref="tree"
  :default-expand-all="true">
</el-tree>
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="getchecked">确 定</el-button>
  </span>
</el-dialog>
</div>

  <!-- 编辑角色信息 -->

<!--角色添加 -->
     <el-dialog
        title="添加角色"
        :visible.sync="dialogVisible1"
        width="40%"
      >
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="70px"
          class="demo-ruleForm"
        >
        <el-form-item label="角色名称" prop="roleName">
      <el-input
              type="text"
              v-model="ruleForm.roleName"
              autocomplete="off"
            ></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
              <el-input
              type="text"
              v-model="ruleForm.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
<!-- 角色添加 -->
    <!-- 修改角色信息 -->
     <el-dialog
        title="修改角色"
        :visible.sync="dialogVisible2"
        width="40%"
      >
        <el-form
          :model="ruleForm1"
          status-icon
          :rules="rules"
          ref="ruleForm1"
          label-width="70px"
          class="demo-ruleForm"
        >
        <el-form-item label="角色名称" prop="roleName">
      <el-input
              type="text"
              v-model="ruleForm1.roleName"
              autocomplete="off"
            ></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
              <el-input
              type="text"
              v-model="ruleForm1.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm1('ruleForm1')">取 消</el-button>
          <el-button type="primary" @click="submitForm1('ruleForm1')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

    <!-- 修改角色信息 -->


  
  </div>
</template>
<script>
import bread from "../../common/breadcrumb";
export default {
  name: "roles",
  data() {
    return {
      link: ["权限管理", "角色列表"],
      tableData: [{}],
      dialogVisible: false, //控制分配权限显示
      defaultProps: {
        children: "children",
        label: "authName",
      },
      roledata: [], //权限数据
      roleid: [], //需要默认选中的权限id
      pid: "", //获取当前角色的id

      dialogVisible1: false, //控制添加角色框打开，
      ruleForm: { //添加用户的数据存放
        roleDesc: "",
        roleName: "",
      },
      ruleForm1: { //修改信息的储存
        roleDesc: "",
        roleName: "",
      },

      dialogVisible2: false, //修改角色信息

      pids:"",//记录修改当前信息的id值

      

      //表单数据规则
      rules: {
        roleName: [
          { required: true, trigger: "blur", message: "用户格式错误" },
        ],
        roleDesc: [
          { required: true, trigger: "blur", message: "用户格式错误" },
        ],
      },
    };
  },
  methods: {
    async getrole() {
      let data = await this.$http.get("roles");
      if (data.meta.status !== 200)
        return this.$message.error("角色列表获取失败");
      this.tableData = data.data;
    },

    // 删除角色指定权限
    async removeright(role, id) {
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erroe) => erroe);

      if (result !== "confirm") return this.$message.warning("取消删除");
      this.$http.delete(`roles/${role.id}/rights/${id}`).then((mes) => {
        role.children = mes.data;
      });
    },

    //删除角色
    async del(id) {
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erroe) => erroe);

      if (result !== "confirm") return this.$message.warning("取消删除");
      let data = await this.$http.delete(`roles/${id}`);

      if (data.meta.status !== 200) return this.$message.info("删除失败");
      this.$message.success("删除成功");
      this.getrole();
    },
    //打开分配权限列表
    async openrole(role) {
      this.dialogVisible = true;
      this.pid = role.id;
      let mes = await this.$http.get("rights/tree");
      this.roledata = mes.data;
      this.selectid(role);
    },
    //匹配到当前权限的id值，默认选中
    selectid(role) {
      this.roleid = [];
      role.children.forEach((item, index, arr) => {
        item.children.forEach((ir, ind, ar) => {
          ir.children.forEach((items) => {
            this.roleid.push(items.id);
          });
        });
      });
    },

    //提交修改后的权限分配
    async getchecked() {
      let idList = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());

      let mes = await this.$http.post(`roles/${this.pid}/rights`, {
        rids: idList.toString(),
      });

      if (mes.meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success("分配成功");
      this.getrole();
      this.dialogVisible = false;
    },
    //打开添加角色框
    openadd() {
      this.dialogVisible1 = true;
    },
    //取消提交
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible1 = false;
    },
    //提交添加
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let mes = await this.$http.post("roles", this.ruleForm);
          if (mes.meta.status !== 201) return this.$message.error("添加失败");
          this.$message.success("添加成功");
          this.dialogVisible1 = false;
          this.getrole();
        } else {
          return false;
        }
      });
    },

    //打开修改信息。
    openedit(row) {
      this.dialogVisible2 = true
      this.ruleForm1.roleDesc = row.roleDesc;
      this.ruleForm1.roleName = row.roleName;
      this.pids = row.id
    },
    //提交修改
     submitForm1(formName){
        this.$refs[formName].validate(async valid=>{
          if(valid){
             let mes = await this.$http.put(`roles/${this.pids}`,this.ruleForm1)

            if(mes.meta.status !==200) return this.$message.error("修改失败") 
            this.$message.success("修改成功")
            this.dialogVisible2 = false
            this.getrole()
          }else{
              return false

          }
        })
    },
    resetForm1(formName){ //关闭修改框
    this.$refs[formName].resetFields();
      this.dialogVisible2 = false;
    }

  },
  components: {
    bread,
  },
  created() {
    this.getrole();
  },
};
</script>
<style scoped>
.right_wrap {
  margin-top: 20px;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
  text-align: left;
}
.el-tag {
  margin: 10px 0;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.nobdtop {
  border-top: none;
}
.el-col {
  vertical-align: middle;
}
</style>